package com.wcs.exam.controller.biz;

import cn.hutool.core.collection.CollectionUtil;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.dao.po.ExamPaperCiteCountPO;
import com.wcs.exam.dao.ExamDao;
import com.wcs.exam.dao.impl.mapper.entity.Exam;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
@RequiredArgsConstructor
public class PaperCommonBiz extends BaseBiz {

    @NotNull
    private final ExamDao examDao;

    /**
     * 获取试卷被引用状态
     *
     * @param paperIds 试卷信息
     * @return 试卷被引用状态
     */
    public Map<Long, Boolean> getPaperCiteStatus(Collection<Long> paperIds) {
        if (CollectionUtil.isEmpty(paperIds)) {
            return Collections.emptyMap();
        }

        Map<Long, Boolean> citeMap = new HashMap<>();

        // 处理被考试引用
        List<ExamPaperCiteCountPO> paperQuestionCiteCountList = examDao.paperCiteCount(paperIds);
        if (CollectionUtil.isNotEmpty(paperQuestionCiteCountList)) {
            paperQuestionCiteCountList.forEach(item -> citeMap.put(item.getPaperId(), item.getCount() > 0));
        }

        // 处理未被引用数据
        for (Long questionId : paperIds) {
            if (citeMap.containsKey(questionId)) {
                continue;
            }
            citeMap.put(questionId, Boolean.FALSE);
        }
        return citeMap;
    }



    /**
     * 试卷被引用检查
     *
     * @param paperId 试卷ID
     * @return 检查结果(false ： 未被引用 、 true ： 被引用)
     */
    public Boolean citeCheck(Long paperId) {
        // 校验是否被考试引用
        boolean examCite = examDao.lambdaQuery().eq(Exam::getPaperId, paperId).exists();
        if (examCite) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
